<template>
  <MainLayout>
    <div class="order-detail-content">
      <el-result 
        icon="success" 
        title="订单提交成功！" 
        sub-title="您的订单已提交，我们将尽快为您处理"
      >
        <template #extra>
          <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
        </template>
      </el-result>
      
      <el-card style="margin-top: 30px" v-if="order">
        <template #header>
          <span>订单信息</span>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ order.id || order.orderId }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(order.status)">
              {{ getStatusText(order.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="收货人">{{ order.name || order.shippingAddress?.name }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ order.phone || order.shippingAddress?.phone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">
            {{ order.address || (order.shippingAddress ? `${order.shippingAddress.province || ''} ${order.shippingAddress.city || ''} ${order.shippingAddress.address || ''}`.trim() : '') }}
          </el-descriptions-item>
          <el-descriptions-item label="订单总额">
            <span style="color: #f56c6c; font-size: 18px; font-weight: bold">
              ¥{{ (order.totalPrice || 0).toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="运费">¥{{ (order.shippingFee || 0).toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="下单时间" :span="2" v-if="order.createdAt">
            {{ new Date(order.createdAt).toLocaleString('zh-CN') }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <h3>商品清单</h3>
        <el-table :data="order.items" style="width: 100%; margin-top: 20px">
          <el-table-column prop="image" label="商品" width="100">
            <template #default="scope">
              <el-image :src="scope.row.image" style="width: 80px; height: 80px" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="price" label="单价" width="100">
            <template #default="scope">¥{{ scope.row.price }}</template>
          </el-table-column>
          <el-table-column label="数量" width="100">
            <template #default="scope">{{ scope.row.quantity }}</template>
          </el-table-column>
          <el-table-column label="小计" width="100">
            <template #default="scope">
              ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <div v-if="loading" v-loading="loading" element-loading-text="加载订单信息..." style="min-height: 400px;">
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { orderAPI } from '../api'
import { ElMessage } from 'element-plus'
import MainLayout from '../layouts/MainLayout.vue'

const route = useRoute()
const router = useRouter()
const order = ref(null)
const loading = ref(true)

onMounted(async () => {
  const orderId = route.params.id
  
  // 先尝试从localStorage获取（如果服务器重启，数据可能丢失）
  const orders = JSON.parse(localStorage.getItem('orders') || '[]')
  const localOrder = orders.find(o => o.orderId === orderId || o.id === orderId)
  
  if (localOrder) {
    // 如果有本地数据，先显示本地数据，然后在后台尝试更新
    order.value = {
      orderId: localOrder.id || localOrder.orderId,
      id: localOrder.id || localOrder.orderId,
      name: localOrder.name || localOrder.shippingAddress?.name || '',
      phone: localOrder.phone || localOrder.shippingAddress?.phone || '',
      address: localOrder.address || (localOrder.shippingAddress ? 
        `${localOrder.shippingAddress.province || ''} ${localOrder.shippingAddress.city || ''} ${localOrder.shippingAddress.address || ''}`.trim() : ''),
      shippingAddress: localOrder.shippingAddress,
      totalPrice: localOrder.totalPrice || 0,
      shippingFee: localOrder.shippingFee || 10,
      items: localOrder.items || [],
      status: localOrder.status || 'pending',
      createdAt: localOrder.createdAt
    }
    loading.value = false
    
    // 静默尝试从API更新（如果服务器已重启，会失败但不显示错误）
    try {
      const response = await orderAPI.getOrderById(orderId)
      if (response && response.success && response.data) {
        // 更新订单数据
        order.value = {
          orderId: response.data.id,
          id: response.data.id,
          name: response.data.shippingAddress?.name || '',
          phone: response.data.shippingAddress?.phone || '',
          address: response.data.shippingAddress?.address || '',
          shippingAddress: response.data.shippingAddress,
          totalPrice: response.data.totalPrice || 0,
          shippingFee: 10,
          items: response.data.items || [],
          status: response.data.status || 'pending',
          createdAt: response.data.createdAt
        }
        // 更新localStorage
        const existingIndex = orders.findIndex(o => o.id === orderId || o.orderId === orderId)
        if (existingIndex >= 0) {
          orders[existingIndex] = response.data
        }
        localStorage.setItem('orders', JSON.stringify(orders))
      }
    } catch (error) {
      // 静默失败，不显示错误（因为已经有本地数据了）
      console.log('从服务器更新订单失败，使用本地缓存数据:', error.response?.status)
    }
    return
  }
  
  // 如果没有本地数据，从API获取
  try {
    const response = await orderAPI.getOrderById(orderId)
    
    if (response && response.success && response.data) {
      // 转换数据格式以匹配页面显示
      order.value = {
        orderId: response.data.id,
        id: response.data.id,
        name: response.data.shippingAddress?.name || '',
        phone: response.data.shippingAddress?.phone || '',
        address: response.data.shippingAddress?.address || '',
        shippingAddress: response.data.shippingAddress,
        totalPrice: response.data.totalPrice || 0,
        shippingFee: 10,
        items: response.data.items || [],
        status: response.data.status || 'pending',
        createdAt: response.data.createdAt
      }
      // 保存到localStorage
      orders.push(response.data)
      localStorage.setItem('orders', JSON.stringify(orders))
    } else {
      ElMessage.error('订单不存在')
      router.push('/')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    
    if (error.response?.status === 404) {
      ElMessage.error('订单不存在')
      router.push('/')
    } else if (error.response?.status === 403) {
      ElMessage.error('无权访问此订单')
      router.push('/')
    } else {
      ElMessage.error(`获取订单详情失败: ${error.response?.data?.message || error.message || '请重试'}`)
    }
  } finally {
    loading.value = false
  }
})

const getStatusText = (status) => {
  const map = {
    pending: '待处理',
    processing: '处理中',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status || '待处理'
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    processing: 'info',
    shipped: '',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || 'warning'
}
</script>

<style scoped>
.order-detail-content {
  padding: 20px 0;
}
</style>

